package top.broncho.mvvm.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import kotlin.math.abs

abstract class BaseBehavior constructor(
    context: Context?,
    attrs: AttributeSet?
) : CoordinatorLayout.Behavior<View>(context, attrs) {
    protected var canInit = true
    protected var animateHelper: AnimateHelper? = null

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout, child: View,
        directTargetChild: View, target: View, axes: Int, type: Int
    ): Boolean {
        return axes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
    }

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {
        onNestPreScrollInit(child)
        if (abs(dy) > 2) {
            if (dy < 0) {
                if (animateHelper?.state == STATE_HIDE) {
                    animateHelper?.show()
                }
            } else if (dy > 0) {
                if (animateHelper?.state == STATE_SHOW) {
                    animateHelper?.hide()
                }
            }
        }
    }

    protected abstract fun onNestPreScrollInit(child: View?)

}